package love.contact.data;

import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlSerializer;
import wwk.common.sqlite.SqliteUtil;
import android.content.Context;
import android.database.Cursor;
import android.os.Handler;
import android.util.SparseBooleanArray;

public class Group {	
	public String longId;
	public String name;

	public SqliteUtil sqliteUtil;

	private Cursor subGroupCursor;
	private Cursor subContactCursor;
	
	public Group(Cursor cursor,SqliteUtil sqliteUtil)
	{
		name=cursor.getString(cursor.getColumnIndex("name"));
		longId=cursor.getString(cursor.getColumnIndex("id"));//id is longId in db
		this.sqliteUtil=sqliteUtil;
	}
	
	public Group(String groupId,String groupName,SqliteUtil sqliteUtil)
	{
		name=groupName;
		longId=groupId==null?"":groupId;
		this.sqliteUtil=sqliteUtil;
	}
	
	static public String getLongName(SqliteUtil sqliteUtil,String groupId,String spliter)
	{
		String longName="";
		String selection=String.format("id='%s'",groupId);
		int lastIndex=groupId.lastIndexOf("-");
		while(lastIndex>=0)
		{
			groupId=groupId.substring(0,lastIndex);
			selection+=String.format(" or id='%s'",groupId);
			lastIndex=groupId.lastIndexOf("-");
		}
		
		Cursor cursor=sqliteUtil.query("groups",null,selection,null,null,null,"id");
		while(cursor.moveToNext())
		{
			Group group=new Group(cursor,null);
			if(longName.length()>0)
			{
				longName+="-";
			}
			longName+=group.getName();
		}
		cursor.close();
		
		return longName;
	}

	public String getName() {
		return name==null?"":name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public String toString()
	{
		return name;
	}
	
	static private int getShortId(String longId)
	{
		int id=-1;
		if(longId!=null)
		{
			String[] strArray=longId.split("-");
			if(strArray.length>0)
			{
				id=Integer.valueOf(strArray[strArray.length-1]).intValue();
			}
		}
		return id;
	}
	
	/*********************************sub contact******************************************/
	public boolean addSubContact(Contact contact)
	{
		String sql=String.format("insert into contact_group (contactId,groupId) values(%d,'%s')",contact.getId(),longId);
		boolean ret=sqliteUtil.executeSql(sql); 
		
		return ret;
	}
	
	public boolean addSubContact(int contactId)
	{
		String sql=String.format("insert into contact_group (contactId,groupId) values(%d,'%s')",contactId,longId);
		boolean ret=sqliteUtil.executeSql(sql); 
		
		return ret;
	}
	
//	public Contact removeSubContact(int index)
//	{
//		String sql=String.format("delete from contact_group where contactId=%d",contact.getId());
//		sqliteUtil.executeSql(sql); 
//		
//		return contact;
//	}

	public boolean addSubGroup(String subGroupName)
	{
		String newSubGroupId=getNextSubGroupId();
		return Group.insert(sqliteUtil, newSubGroupId, subGroupName);
	}

	public Group subGroupAtIndex(int index) 
	{
		if(subGroupCursor!=null && subGroupCursor.moveToPosition(index))
		{
			return new Group(subGroupCursor,sqliteUtil);
		}
		
		return null;
	}
	
	public int subContactId(Context context,int index) 
	{
		if(subContactCursor!=null && subContactCursor.moveToPosition(index))
		{
			int contactId=subContactCursor.getInt(subContactCursor.getColumnIndex("contactId"));
			return contactId;
		}
		
		return 0;
	}
	
	/*********************************db******************************************/
	static public boolean createTable(SqliteUtil sqliteUtil)
	{
		String sql="create table IF NOT EXISTS groups (id varchar(10) primary key, name varchar(50))";
		boolean ret=sqliteUtil.executeSql(sql); 
		
		if(ret)
		{
			sql="create table IF NOT EXISTS contact_group (contactId INTEGER primary key, groupId varchar(10))";
			ret=sqliteUtil.executeSql(sql);
		}
		
		/*
		String sql="drop table groups";
		boolean ret=sqliteUtil.executeSql(sql); 
		if(ret)
		{
			sql="drop table contact_group";
			ret=sqliteUtil.executeSql(sql);
		}
		*/
		
		return ret;
	}
	
//	static private boolean isGroupExists(SqliteUtil sqliteUtil,String longId)
//	{
//		if(longId!=null && longId.length()>0)
//		{
//			String[] columns={"count(*)"};
//			String selection=String.format("id = '%s'",longId);
//			Cursor cursor=sqliteUtil.query("groups",columns,selection,null,null,null,null);
//			if(cursor.moveToFirst())
//			{
//				int count=cursor.getInt(0);
//				return count>0;
//			}
//		}
//		
//		return false;
//	}
		
	//update group name in db
	public boolean update()
	{
		return Group.update(sqliteUtil, longId, name);
	}
	
	static public boolean update(SqliteUtil sqliteUtil,String groupId,String groupName)
	{
		if(groupId!=null && groupId.length()>0 && groupName!=null && groupName.length()>0)
		{
			String sql=String.format("update groups set name='%s' where id='%s'",groupName,groupId);
			return sqliteUtil.executeSql(sql); 
		}
		
		return false;
	}

	static public boolean insert(SqliteUtil sqliteUtil,String groupId,String groupName)
	{
		if(groupId!=null && groupId.length()>0 && groupName!=null && groupName.length()>0)
		{
			String sql=String.format("insert into groups (name,id) values('%s','%s')",groupName,groupId);
			return sqliteUtil.executeSql(sql); 
		}
		
		return false;
	}
	
	static public boolean insertContactGroup(SqliteUtil sqliteUtil,String groupId,int contactId)
	{
		boolean ret=false;
		
		if(groupId!=null && groupId.length()>0)
		{
			String sql=String.format("insert into contact_group (contactId,groupId) values(%d,'%s')",contactId,groupId);
			ret = sqliteUtil.executeSql(sql); 
		}

		return ret;
	}
	
	//delete group with groupLongId
	public boolean delete()
	{
		boolean ret=false;

		if(longId!=null && longId.length()>0)
		{
			String sql=String.format("delete from groups where id like '%s%%' ",longId);
			ret=sqliteUtil.executeSql(sql); 
			
			sql=String.format("delete from contact_group where groupId like '%s%%' ",longId);
			ret=sqliteUtil.executeSql(sql); 
		}
		else
		{
			Group.deleteAll(sqliteUtil);
		}

		return ret;
	}
	
	public boolean removeSubContact(int contactId)
	{
		String sql=String.format("delete from contact_group where contactId = %d",contactId);
		boolean ret=sqliteUtil.executeSql(sql); 
		return ret;
	}
	
	static public boolean deleteAll(SqliteUtil sqliteUtil)
	{
		String sql=String.format("delete from groups");
		boolean ret=sqliteUtil.executeSql(sql); 
		
		sql=String.format("delete from contact_group");
		ret=sqliteUtil.executeSql(sql); 
		
		return ret;
	}
	
//	static private boolean delete(SqliteUtil sqliteUtil,String groupLongId)
//	{
//		boolean ret=false;
//		
//		String longId=groupLongId;
//		if(longId!=null && longId.length()>0)
//		{
//			String sql=String.format("delete from groups where id like '%s%%' ",longId);
//			ret=sqliteUtil.executeSql(sql); 
//			
//			deleteFromContactGroup(sqliteUtil,groupLongId);
//		}
//		
//		return ret;
//	}
	
//	static private boolean deleteFromContactGroup(SqliteUtil sqliteUtil,String groupLongId)
//	{
//		boolean ret=false;
//		
//		String longId=groupLongId;
//		if(longId!=null && longId.length()>0)
//		{
//			String sql=String.format("delete from contact_group where groupId like '%s%%' ",longId);
//			ret=sqliteUtil.executeSql(sql); 
//		}
//		
//		return ret;
//	}

	public void addSubContacts(List<Contact> ungroupedContactArray,List<Integer> ungroupedContactIdArray,SparseBooleanArray sparseBooleanArray)
	{
		//can not remove while traversal
		List<Contact> tempContactArray=new ArrayList<Contact>();
		
		int size=sparseBooleanArray.size();
		for(int i=0;i<size;i++)
		{
			 int index=sparseBooleanArray.keyAt(i);
			 Contact contact=ungroupedContactArray.get(index);
			 boolean ret=addSubContact(contact);
			 if(ret)
			 {
				 tempContactArray.add(contact);
			 }
		}
		
		for(Contact contact : tempContactArray)
		{
			ungroupedContactArray.remove(contact);
			ungroupedContactIdArray.remove( new Integer(contact.getId()));//ע�⣬����Ǵ�int����ͳ��˸�������Ƴ��ˡ�
		}
	}

	private void openSubContactCursor()
	{
		String selection=String.format("groupId = '%s'",longId);
		if(subContactCursor!=null)
		{
			subContactCursor.close();
		}
		subContactCursor=sqliteUtil.query("contact_group",null,selection,null,null,null,"contactId");
		subContactCursor.moveToFirst();
	}
	
	static public String ungroupedContactIdsSelectionString(SqliteUtil sqliteUtil)
	{
		Cursor cursor=sqliteUtil.query("contact_group",new String[]{"contactId"},null,null,null,null,"contactId");
	
		StringBuffer buf=null;
		
		boolean b=cursor.moveToFirst();
		if(b)
		{
			buf=new StringBuffer();
			buf.append("(");
		}
		
		while(b)
		{
			int contactId=cursor.getInt(0);
			buf.append(""+contactId+"");
			b=cursor.moveToNext();
			if(b)
			{
				buf.append(",");
			}
			else
			{
				buf.append(")");
			}
		}
		
		cursor.close();
		
		if(buf!=null)
		{
			return buf.toString();
		}
		
		return null;
	}
	
	public int subGroupCount()
	{
		if(subGroupCursor!=null)
			return subGroupCursor.getCount();
		
		return 0;
	}
	
	public int subContactCount()
	{
		if(subContactCursor!=null)
			return subContactCursor.getCount();
		
		return 0;
	}
	
	static public int groupCount(SqliteUtil sqliteUtil)
	{
		int count=0;
		
		String[] columns={"count(*)"};
		Cursor cursor=sqliteUtil.query("groups",columns,null,null,null,null,null);
		if(cursor.moveToFirst())
		{
			count=cursor.getInt(0);
		}
		cursor.close();
		
		return count;
	}
	
	//longId
	private String getNextSubGroupId()
	{
		int maxSubGroupShortId=0;
		
		String selection="";
		if(longId.length()>0)
		{
			selection=String.format("id like '%s-%%' and id not like '%s-%%-%%'",longId,longId);
		}
		else
		{
			selection=String.format("id not like '%%-%%'");
		}
		Cursor cursor=sqliteUtil.query("groups",null,selection,null,null,null,"id desc");
		if(cursor.moveToFirst())
		{
			String maxSubGroupLongId=cursor.getString(cursor.getColumnIndex("id"));
			maxSubGroupShortId=getShortId(maxSubGroupLongId);
		}
		cursor.close();
		
		String nextSubGroupId=null;
		if(longId.length()>0)
		{
			nextSubGroupId=String.format("%s-%d",longId,++maxSubGroupShortId);
		}
		else
		{
			nextSubGroupId=String.format("%d",++maxSubGroupShortId);
		}
		
		return nextSubGroupId;
	}
	
	//load subgroups from db
	private void openSubGroupCursor()
	{
		String selection="";
		if(longId.length()>0)
		{
			selection=String.format("id like '%s-%%' and id not like '%s-%%-%%'",longId,longId);
		}
		else
		{
			selection=String.format("id not like '%%-%%'");
		}
		if(subGroupCursor!=null)
		{
			subGroupCursor.close();
		}
		
		subGroupCursor=sqliteUtil.query("groups",null,selection,null,null,null,"name COLLATE LOCALIZED ASC");
		subGroupCursor.moveToFirst();
	}
	
	public void openSubCursor()
	{
		openSubGroupCursor();
		openSubContactCursor();
	}
	
//	static public void importe(XmlPullParser parser,SqliteUtil sqliteUtil,Handler handler)
//	{		
//		try 
//		{
//	        int eventType = parser.next();
//			while (eventType != XmlPullParser.END_DOCUMENT) 
//			{
//				if (eventType == XmlPullParser.START_TAG) 
//				{
//					String tagName=parser.getName();
//					if(tagName.equals("group"))
//					{
//						
//					}//end group
//				}
//				else if (eventType == XmlPullParser.END_TAG) 
//				{
//					String tagName=parser.getName();
//					if(tagName.equals("groups"))
//					{
//						break;
//					}
//				} 
//				
//				eventType = parser.next();
//			}
//		} 
//		catch (XmlPullParserException e) 
//		{ 
//			e.printStackTrace();
//		}
//		catch (IOException e) 
//		{ 
//			e.printStackTrace();
//		}
//	}
	
	static public void export(XmlSerializer serializer,SqliteUtil sqliteUtil,Handler handler)
	{
	    try 
	    {
	    	//groups
	    	serializer.startTag("", "groups");
	        Cursor cursor=sqliteUtil.query("groups",null,null,null,null,null,"id");
			boolean bool=cursor.moveToFirst();
			while(bool)
			{
				String name=cursor.getString(cursor.getColumnIndex("name"));
				String longId=cursor.getString(cursor.getColumnIndex("id"));
				bool=cursor.moveToNext();
				
				serializer.startTag("", "group");
		        serializer.attribute("", "name", name);
		        serializer.attribute("", "id", longId);
		        serializer.endTag("", "group");
		        
		        handler.sendEmptyMessage(ContactConst.MSG_IMPORT_INCREASE);
			}
			cursor.close();
			serializer.endTag("", "groups");

	        //contactId_groupId
	        serializer.startTag("", "contact_group");
	        cursor=sqliteUtil.query("contact_group",null,null,null,null,null,"groupId");
			bool=cursor.moveToFirst();
			while(bool)
			{
				int contactId=cursor.getInt(cursor.getColumnIndex("contactId"));
				String groupId=cursor.getString(cursor.getColumnIndex("groupId"));
				bool=cursor.moveToNext();
				
				serializer.startTag("", "contact_group_item");
				serializer.attribute("", "contact_id", ""+contactId);
		        serializer.attribute("", "group_id", groupId);
		        serializer.endTag("", "contact_group_item");
			}
			cursor.close();
	        serializer.endTag("", "contact_group");
	    } 
	    catch (Exception e) 
	    {
	        e.printStackTrace();
	    }
	}
	
	public void closeCusror()
	{
		if(subGroupCursor!=null)
		{
			subGroupCursor.close();
			subGroupCursor=null;
		}
		
		if(subContactCursor!=null)
		{
			subContactCursor.close();
			subGroupCursor=null;
		}
	}
}
